package com.mushuilingfeng.ddd.user.infrastructure.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.mushuilingfeng.ddd.user.domain.user.entity.UserLoginDevice;
import com.mushuilingfeng.ddd.user.domain.user.repository.IUserLoginDeviceRepository;
import com.mushuilingfeng.ddd.user.infrastructure.cover.IPODataCover;
import com.mushuilingfeng.ddd.user.infrastructure.repository.dao.mapperservice.UserLoginDeviceMapperService;
import com.mushuilingfeng.ddd.user.infrastructure.repository.po.UserLoginDevicePO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 沐水淋风
 * @date 2024/10/6
 */
@Repository
@AllArgsConstructor
public class UserLoginDeviceRepositoryImpl extends BaseMybatisRepository<UserLoginDevice> implements IUserLoginDeviceRepository {
    private final UserLoginDeviceMapperService mapperService;
    
    @Override
    public int getLoginDeviceCount(Long userId) {
        return mapperService.lambdaQuery().eq(UserLoginDevicePO::getUserId, userId).count().intValue();
    }
    
    @Override
    public UserLoginDevice getByUserIdAndDeviceCode(Long userId, String deviceCode) {
        List<UserLoginDevicePO> poList = mapperService.lambdaQuery().eq(UserLoginDevicePO::getUserId, userId).eq(UserLoginDevicePO::getDeviceCode,
                deviceCode).list();
        if (CollectionUtil.isEmpty(poList)) {
            return null;
        }
        return IPODataCover.INSTANCE.userLoginDevicePO2UserLoginDevice(poList.get(0));
    }
    
    @Override
    public List<UserLoginDevice> listByUserId(Long userId) {
        List<UserLoginDevicePO> poList = mapperService.lambdaQuery().eq(UserLoginDevicePO::getUserId, userId).list();
        if (CollectionUtil.isEmpty(poList)) {
            return Collections.emptyList();
        }
        return IPODataCover.INSTANCE.userLoginDevicePOList2UserLoginDeviceList(poList);
    }
    
    @Override
    public void updateLastLoginTime(Long id, Date lastLoginTime) {
        mapperService.lambdaUpdate().set(UserLoginDevicePO::getLastLoginTime, lastLoginTime).eq(UserLoginDevicePO::getId, id).update();
    }
    
    @Override
    public UserLoginDevice get(Serializable id) {
        UserLoginDevicePO po = mapperService.getById(id);
        if (null == po) {
            return null;
        }
        return IPODataCover.INSTANCE.userLoginDevicePO2UserLoginDevice(po);
    }
    
    @Override
    public void save(UserLoginDevice entityOrObjectValue) {
        mapperService.save(IPODataCover.INSTANCE.userLoginDevice2UserLoginDevicePO(entityOrObjectValue));
    }
    
    @Override
    public void saveOrUpdate(UserLoginDevice entityOrObjectValue) {
        throw new RuntimeException("not support saveOrUpdate method!");
    }
    
    @Override
    public void delete(Serializable id) {
        mapperService.removeById(id);
    }
    
}
